// 当页面加载时重置隐藏状态
chrome.storage.local.remove(['hideFloatingButton']);

// 创建浮动按钮和侧边栏
function createFloatingButton() {
    // 创建侧边栏容器
    const sidebar = document.createElement('div');
    sidebar.id = 'openai-chat-sidebar';
    sidebar.style.position = 'fixed';
    sidebar.style.top = '0';
    sidebar.style.right = '-400px';
    sidebar.style.width = '400px';
    sidebar.style.height = '100%';
    sidebar.style.backgroundColor = 'white';
    sidebar.style.boxShadow = '-2px 0 5px rgba(0,0,0,0.1)';
    sidebar.style.transition = 'right 0.3s ease';
    sidebar.style.zIndex = '9999';
    
    // 创建拖动条
    const resizer = document.createElement('div');
    resizer.style.width = '4px';
    resizer.style.height = '100%';
    resizer.style.position = 'absolute';
    resizer.style.left = '0';
    resizer.style.top = '0';
    resizer.style.backgroundColor = 'transparent';
    resizer.style.cursor = 'col-resize';
    resizer.style.zIndex = '10000';

    // HTML转义函数
    function escapeHtml(text) {
        const htmlEscapes = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        };
        return text.replace(/[&<>"']/g, char => htmlEscapes[char]);
    }

    // 处理消息显示
    // 处理代码块的辅助函数
function processCodeBlock(line, isInCodeBlock, codeBlockContent) {
    if (line.startsWith('```')) {
        if (!isInCodeBlock) {
            return {
                isInCodeBlock: true,
                content: '<pre><code>',
                codeBlockContent: ''
            };
        } else {
            return {
                isInCodeBlock: false,
                content: escapeHtml(codeBlockContent) + '</code></pre>',
                codeBlockContent: ''
            };
        }
    }
    return null;
}

// 处理行内代码的辅助函数
function processInlineCode(line) {
    const inlineCodeRegex = /`([^`]+)`/g;
    return line.replace(inlineCodeRegex, (_, code) => 
        `<code class="inline-code">${escapeHtml(code)}</code>`
    );
}

function processMessage(content) {
        if (!content) return '';
        
        let processedContent = '';
        let isInCodeBlock = false;
        let codeBlockContent = '';
        
        const lines = content.split('\n');
        for (const line of lines) {
            const codeBlockResult = processCodeBlock(line, isInCodeBlock, codeBlockContent);
            
            if (codeBlockResult) {
                isInCodeBlock = codeBlockResult.isInCodeBlock;
                processedContent += codeBlockResult.content;
                codeBlockContent = codeBlockResult.codeBlockContent;
            } else if (isInCodeBlock) {
                codeBlockContent += line + '\n';
            } else {
                processedContent += processInlineCode(line) + '\n';
            }
        }
        
        // 移除最后一个换行符
        return processedContent.trim();
    }

    // 创建iframe来加载聊天界面
    const iframe = document.createElement('iframe');
    iframe.style.width = '100%';
    iframe.style.height = '100%';
    iframe.style.border = 'none';
    iframe.style.backgroundColor = 'white';
    
    // 设置iframe内容
    iframe.onload = function() {
        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        
        // 添加样式链接
        const styleLink = document.createElement('link');
        styleLink.rel = 'stylesheet';
        styleLink.href = chrome.runtime.getURL('styles.css');
        iframeDoc.head.appendChild(styleLink);
        
        // 添加 Material Icons
        const materialIconsLink = document.createElement('link');
        materialIconsLink.rel = 'stylesheet';
        materialIconsLink.href = 'https://fonts.googleapis.com/icon?family=Material+Icons';
        iframeDoc.head.appendChild(materialIconsLink);
        
        // 设置内容
        iframeDoc.body.innerHTML = `
            <div class="container">
                <div class="header">
                    <h1>AI助手</h1>
                    <div class="header-buttons">
                        <button id="clear-history" class="icon-button" title="清除历史记录">
                            <span class="material-icons">delete</span>
                        </button>
                        <button id="settings-button" class="icon-button" title="设置">
                            <span class="material-icons">settings</span>
                        </button>
                    </div>
                </div>
                
                <div class="chat-container">
                    <div id="chat-messages"></div>
                    
                    <div class="input-container">
                        <div class="input-wrapper">
                            <textarea id="message-input" placeholder="输入消息..."></textarea>
                            <div class="buttons">
                                <button id="send-message">发送</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 添加类名
        iframeDoc.body.classList.add('sidepanel');

        // 获取DOM元素
        const settingsButton = iframeDoc.getElementById('settings-button');
        const clearHistoryButton = iframeDoc.getElementById('clear-history');
        const sendButton = iframeDoc.getElementById('send-message');
        const messageInput = iframeDoc.getElementById('message-input');
        const chatMessages = iframeDoc.getElementById('chat-messages');

        // 加载历史记录
        function loadChatHistory() {
            chrome.storage.local.get(['chatHistory'], function(result) {
                if (result.chatHistory) {
                    result.chatHistory.forEach(msg => {
                        const messageDiv = document.createElement('div');
                        messageDiv.className = 'message ' + (msg.role || 'user');
                        if (msg.role === 'assistant') {
                            messageDiv.classList.add('done');
                        }
                        messageDiv.innerHTML = processMessage(msg.content);
                        chatMessages.appendChild(messageDiv);
                    });
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
            });
        }

        // 保存消息到历史记录
        function saveMessage(role, content) {
            chrome.storage.local.get(['chatHistory'], function(result) {
                const chatHistory = result.chatHistory || [];
                chatHistory.push({
                    role: role,
                    content: content,
                    timestamp: new Date().toISOString()
                });
                chrome.storage.local.set({ chatHistory: chatHistory });
            });
        }

        // 清除历史记录
        clearHistoryButton.addEventListener('click', () => {
            if (confirm('确定要清除所有聊天记录吗？')) {
                chrome.storage.local.remove(['chatHistory'], function() {
                    chatMessages.innerHTML = '';
                });
            }
        });

        // 修改消息显示函数
        function appendMessage(role, content, save = true) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + (role || 'user');
            if (role === 'assistant') {
                messageDiv.classList.add('done');
            }
            messageDiv.innerHTML = processMessage(content);
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
            
            if (save) {
                saveMessage(role, content);
            }
        }

        // 加载历史记录
        loadChatHistory();

        // 处理设置按钮点击
        settingsButton.addEventListener('click', () => {
            window.parent.postMessage({ type: 'openSettings' }, '*');
        });

        // 添加消息显示函数
        const messageHandler = (event) => {
            const data = event.data;
            if (data.type === 'appendMessage') {
                // 创建新消息元素
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message ' + (data.role || 'user');
                if (data.role === 'assistant') {
                    messageDiv.classList.add('done');
                }
                messageDiv.innerHTML = processMessage(data.content);
                chatMessages.appendChild(messageDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;
                
                // 保存消息到历史记录
                saveMessage(data.role || 'user', data.content);
            } else if (data.type === 'saveMessage') {
                // 只保存消息到历史记录，不显示（用于保存完整的AI响应）
                saveMessage(data.role, data.content);
            }
        };

        // 在iframe文档中添加消息监听
        iframeDoc.defaultView.addEventListener('message', messageHandler);

        // 处理发送按钮点击
        sendButton.addEventListener('click', () => {
            const message = messageInput.value.trim();
            if (message) {
                // 发送消息到父窗口
                window.parent.postMessage({ 
                    type: 'sendMessage',
                    message: message
                }, '*');
                messageInput.value = '';
            }
        });

        // 添加回车发送功能
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendButton.click();
            }
        });
    };
    
    iframe.src = 'about:blank';

    // 监听来自iframe的消息
    window.addEventListener('message', async (event) => {
        const data = event.data;
        
        switch (data.type) {
            case 'openSettings':
                // 打开设置页面
                chrome.runtime.sendMessage({ type: 'openSettings' });
                break;
                
            case 'sendMessage':
                try {
                    // 获取聊天消息容器和函数
                    const chatMessages = iframe.contentDocument.getElementById('chat-messages');
                    const iframeWindow = iframe.contentWindow;
                    
                    // 检查是否已经存在相同的用户消息
                    const existingUserMessage = chatMessages.querySelector('.message.user:last-child');
                    if (existingUserMessage && existingUserMessage.textContent === data.message) {
                        // 如果已经存在相同的用户消息，则不再添加
                        return;
                    }

                    // 添加用户消息
                    iframeWindow.postMessage({
                        type: 'appendMessage',
                        role: 'user',
                        content: data.message
                    }, '*');

                    let accumulatedContent = '';
                    let responseDiv;

                    // 创建一个消息监听器
                    const messageListener = (message) => {
                        if (message.type === 'streamContent') {
                            if (!responseDiv) {
                                // 第一次收到响应时创建响应div
                                responseDiv = document.createElement('div');
                                responseDiv.className = 'message assistant';
                                chatMessages.appendChild(responseDiv);
                            }
                            
                            // 累积内容
                            accumulatedContent += message.content;
                            
                            // 处理并显示内容
                            const processedContent = processMessage(accumulatedContent);
                            responseDiv.innerHTML = processedContent;
                            
                            chatMessages.scrollTop = chatMessages.scrollHeight;
                        } else if (message.type === 'streamError') {
                            if (!responseDiv) {
                                iframeWindow.postMessage({
                                    type: 'appendMessage',
                                    role: 'assistant',
                                    content: '错误: ' + message.error
                                }, '*');
                            } else {
                                responseDiv.textContent = '错误: ' + message.error;
                                responseDiv.classList.add('error');
                            }
                            chrome.runtime.onMessage.removeListener(messageListener);
                        } else if (message.type === 'streamEnd') {
                            if (responseDiv) {
                                responseDiv.classList.add('done');
                                // 通过iframe的window发送保存消息的请求
                                iframeWindow.postMessage({
                                    type: 'saveMessage',
                                    role: 'assistant',
                                    content: accumulatedContent
                                }, '*');
                            }
                            chrome.runtime.onMessage.removeListener(messageListener);
                        }
                    };

                    // 添加消息监听器
                    chrome.runtime.onMessage.addListener(messageListener);

                    // 发送消息到background.js
                    const response = await chrome.runtime.sendMessage({ 
                        type: 'sendMessage',
                        message: data.message
                    });

                    if (response && response.error) {
                        iframeWindow.postMessage({
                            type: 'appendMessage',
                            role: 'assistant',
                            content: '错误: ' + response.error
                        }, '*');
                        chrome.runtime.onMessage.removeListener(messageListener);
                    }
                } catch (error) {
                    console.error('Error sending message:', error);
                    iframe.contentWindow.postMessage({
                        type: 'appendMessage',
                        role: 'assistant',
                        content: '发送消息时出错: ' + error.message
                    }, '*');
                }
                break;
                
            case 'uploadFile':
                // 处理文件上传
                try {
                    const response = await chrome.runtime.sendMessage({
                        type: 'uploadFile',
                        file: data.file,
                        fileName: data.fileName
                    });
                    
                    if (response && response.content) {
                        const messageDiv = document.createElement('div');
                        messageDiv.className = 'message assistant';
                        messageDiv.textContent = response.content;
                        iframe.contentDocument.getElementById('chat-messages').appendChild(messageDiv);
                    }
                } catch (error) {
                    console.error('Error uploading file:', error);
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'message assistant error';
                    errorDiv.textContent = '上传文件时出错: ' + error.message;
                    iframe.contentDocument.getElementById('chat-messages').appendChild(errorDiv);
                }
                break;
        }
    });

    // 添加拖动功能
    let isResizing = false;
    let startX;
    let startWidth;

    resizer.addEventListener('mousedown', (e) => {
        isResizing = true;
        startX = e.clientX;
        startWidth = parseInt(sidebar.style.width);
        document.body.style.userSelect = 'none';
    });

    document.addEventListener('mousemove', throttle((e) => {
        if (!isResizing) return;
        const width = startWidth + (startX - e.clientX);
        if (width >= 300 && width <= 800) {
            sidebar.style.width = width + 'px';
            if (sidebar.style.right === '0px') {
                buttonContainer.style.right = width + 'px';
            }
        }
    }, 16)); // 限制拖动事件处理频率为每16ms一次，约60fps

    document.addEventListener('mouseup', () => {
        isResizing = false;
        document.body.style.userSelect = '';
    });

    // 组装侧边栏
    sidebar.appendChild(resizer);
    sidebar.appendChild(iframe);
    document.body.appendChild(sidebar);

    // 创建浮动按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.id = 'openai-floating-button-container';
    buttonContainer.style.position = 'fixed';
    buttonContainer.style.right = '0';
    buttonContainer.style.top = '50%';
    buttonContainer.style.transform = 'translateY(-50%)';
    buttonContainer.style.zIndex = '10000';
    buttonContainer.style.cursor = 'pointer';
    buttonContainer.style.width = '60px';
    buttonContainer.style.height = '48px';
    buttonContainer.style.transition = 'right 0.3s ease';
    
    // 创建浮动按钮
    const button = document.createElement('button');
    button.id = 'openai-floating-button';
    button.style.position = 'relative';
    button.style.border = 'none';
    button.style.background = 'white';
    button.style.padding = '6px 20px 6px 10px';
    button.style.cursor = 'pointer';
    button.style.width = '52px';
    button.style.height = '36px';
    button.style.display = 'flex';
    button.style.alignItems = 'center';
    button.style.borderRadius = '18px 0 0 18px';
    button.style.boxShadow = '-2px 2px 4px rgba(0,0,0,0.2)';
    button.style.position = 'absolute';
    button.style.right = '0';
    button.style.top = '6px';
    
    const img = document.createElement('img');
    img.src = chrome.runtime.getURL('images/icon24.png');
    img.alt = 'OpenAI聊天助手';
    img.style.width = '24px';
    img.style.height = '24px';
    img.style.display = 'block';
    img.style.marginRight = '4px';
    
    // 创建关闭按钮
    const closeButton = document.createElement('button');
    closeButton.id = 'openai-close-button';
    closeButton.innerHTML = '×';
    closeButton.style.display = 'none';
    closeButton.style.position = 'absolute';
    closeButton.style.top = '10px';
    closeButton.style.right = '6px';
    closeButton.style.width = '16px';
    closeButton.style.height = '16px';
    closeButton.style.borderRadius = '50%';
    closeButton.style.background = 'transparent';
    closeButton.style.color = '#666';
    closeButton.style.border = 'none';
    closeButton.style.cursor = 'pointer';
    closeButton.style.fontSize = '18px';
    closeButton.style.lineHeight = '16px';
    closeButton.style.padding = '0';
    closeButton.style.zIndex = '10001';
    closeButton.style.textAlign = 'center';
    closeButton.style.fontFamily = 'Arial, sans-serif';
    closeButton.style.userSelect = 'none';
    closeButton.style.opacity = '0.6';
    closeButton.style.transition = 'opacity 0.2s';
    
    // 添加鼠标悬停效果
    closeButton.addEventListener('mouseenter', () => {
        closeButton.style.opacity = '1';
    });
    
    closeButton.addEventListener('mouseleave', () => {
        closeButton.style.opacity = '0.6';
    });
    
    // 鼠标悬停时显示关闭按钮
    buttonContainer.addEventListener('mouseenter', () => {
        closeButton.style.display = 'block';
    });
    
    // 鼠标离开时隐藏关闭按钮
    buttonContainer.addEventListener('mouseleave', () => {
        closeButton.style.display = 'none';
    });
    
    button.appendChild(img);
    button.appendChild(closeButton);
    buttonContainer.appendChild(button);
    document.body.appendChild(buttonContainer);
    
    // 点击关闭按钮时隐藏浮动图标
    closeButton.addEventListener('click', (e) => {
        e.stopPropagation();
        buttonContainer.remove();
        sidebar.remove();
    });
    
    // 点击按钮时切换侧边栏
    button.addEventListener('click', () => {
        const isHidden = sidebar.style.right === '-400px' || sidebar.style.right === '';
        if (isHidden) {
            sidebar.style.right = '0';
            buttonContainer.style.right = sidebar.style.width;
        } else {
            sidebar.style.right = '-400px';
            buttonContainer.style.right = '0';
        }
    });
}

// 添加节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 当页面加载完成时创建浮动按钮
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', createFloatingButton);
} else {
    createFloatingButton();
}
